use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};
use sqlx::mysql::MySqlPool;
use std::sync::Arc;
use dotenvy::dotenv;
use serde_json::json;
use std::env;

// 定义 User 结构体，用于序列化和反序列化
#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: i32,
    name: String,
    email: String,
}

// 定义 AppState 结构体，用于存储数据库连接
struct AppState {
    db: MySqlPool,
}

// 获取单个用户
#[get("/users/{id}")]
async fn get_user(path: web::Path<i32>, data: web::Data<AppState>) -> impl Responder {
    let user_id = path.into_inner();
    let pool = &data.db;

    // 查询用户
    let query_result = sqlx::query_as!(
        User,
        r#"
        select id, name, email from users where id = ?
        "#,
        user_id
    )
        .fetch_optional(pool)
        .await;

    match query_result {
        Ok(Some(user)) => HttpResponse::Ok().json(user),
        Ok(None) => HttpResponse::NotFound().body("用户未找到"),
        Err(_) => HttpResponse::InternalServerError().body("获取用户时出错"),
    }
}

// 创建新用户
#[post("/users")]
async fn create_user(user: web::Json<User>, data: web::Data<AppState>) -> impl Responder {
    let pool = &data.db;

    // 插入用户
    let insert_result = sqlx::query!(
        r#"
        insert into users (name, email) values (?, ?)
        "#,
        user.name,
        user.email
    )
        .execute(pool)
        .await;

    match insert_result {
        Ok(_) => HttpResponse::Created().json(&user),
        Err(_) => HttpResponse::InternalServerError().body("创建用户时出错"),
    }
}

// 获取所有用户
#[get("/users")]
async fn get_all_users(data: web::Data<AppState>) -> impl Responder {
    let pool = &data.db;

    // 查询所有用户
    let query_result = sqlx::query_as!(
        User,
        r#"
        select id, name, email from users
        "#

    )
        .fetch_all(pool)
        .await;

    match query_result {
        Ok(users) => HttpResponse::Ok().json(users),
        Err(_) => HttpResponse::InternalServerError().body("获取用户时出错"),
    }
}




// 主函数，设置数据库连接，并启动 HTTP 服务器
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    dotenv().ok();

    // 加载 .env 文件
    dotenv().expect("未能加载.env文件");
    // 读取环境变量
    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL 必须设置");
    println!("Database URL: {}", database_url);

    let pool = MySqlPool::connect(&database_url).await.expect("创建连接池失败");
    println!("服务器运行在 http://127.0.0.1:8881");

    // 启动 HTTP 服务器
    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(AppState {
                db: pool.clone(),
            }))
            .service(get_user)
            .service(create_user)
            .service(get_all_users)
    })
        .bind(("127.0.0.1", 8881))?
        .run()
        .await
}
